/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rhdtp.demopf.model.dao;

import com.rhdtp.demopf.model.dto.Cliente;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.internal.SessionFactoryImpl;

/**
 *
 * @author rhdtp
 */
public class ClienteDAO extends TemplateDAO<Cliente> {

    private static final Logger logger = Logger.getLogger(ClienteDAO.class);
    private SessionFactoryImpl sessionFactory;

    @Override
    public Cliente load(Cliente t) {
        Session session = sessionFactory.openSession();

        try {
            t = (Cliente) session.load(Cliente.class, t.getId());
        } catch (HibernateException he) {
            logger.error(he.getCause(), he);
        } finally {
            session.clear();
            session.close();
        }

        return t;
    }

    @Override
    public List<Cliente> list() {
        Session session = sessionFactory.openSession();
        List<Cliente> list = null;
        try {
            Criteria c = session.createCriteria(Cliente.class);
            list = c.list();
        } catch (HibernateException he) {
            logger.error(he.getCause(), he);
            return null;
        } finally {
            session.clear();
            session.close();
        }
        return list;
    }

    public int countId() {
        Session session = sessionFactory.openSession();
        String stringQuery;
        Query query;
        int count = 0;

        try {
            stringQuery = "SELECT COUNT(*) FROM Cliente";
            query = session.createQuery(stringQuery);
            count = ((Long) query.uniqueResult()).intValue();
        } catch (HibernateException he) {
            logger.error(he.getCause(), he);
        } finally {
            session.clear();
            session.close();
        }

        return count;
    }

    @Override
    public List<Cliente> search(Cliente t) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    /**
     * @param sessionFactory the sessionFactory to set
     */
    public void setSessionFactory(SessionFactoryImpl sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
